using System;
using System.Collections.Generic;
using System.Text;

namespace GetTogether.Studio
{
    public class Projects<T> : GetTogether.ObjectBase.ListBase<Project<T>>
        where T : class, new()
    {
        public Projects()
        {

        }

        public static Projects<T> GetProjects<T>(GetTogether.Studio.ProjectParameter.ProjectCategory prjCategory, string username)
            where T : class, new()
        {
            Projects<T> ts = GetProjectsByPath<T>(GetTogether.Studio.ProjectParameter.GetSettingsPath(prjCategory, username));
            if (ts == null || ts.Count == 0)
            {
                GetTogether.Utility.DirectoryHelper.Copy(
                    GetTogether.Studio.ProjectParameter.GetSettingsPathPublic(prjCategory),
                    GetTogether.Studio.ProjectParameter.GetSettingsPath(prjCategory, username),
                    false);
                ts = GetProjectsByPath<T>(GetTogether.Studio.ProjectParameter.GetSettingsPath(prjCategory, username));
            }

            return ts;
        }

        public static Projects<T> GetProjectsByPath<T>(string path)
            where T : class, new()
        {
            if (!System.IO.Directory.Exists(path)) System.IO.Directory.CreateDirectory(path);
            Projects<T> pjs = new Projects<T>();
            foreach (string s in System.IO.Directory.GetFiles(path))
            {
                Project<T> pj = new Project<T>();
                System.IO.FileInfo fi = new System.IO.FileInfo(s);
                T p = new T();
                p = GetTogether.Utility.SerializationHelper.FromXml<T>(System.IO.File.ReadAllText(s));
                if (p != null)
                {
                    pj.Parameter = p;
                }
                pj.History = ProjectHistory.GetProjectHistory(path, fi.Name);
                pjs.Add(pj);
            }
            pjs.SortBy("RecentUsed", false);
            return pjs;
        }
    }

    public class Project<T>
        where T : class, new()
    {
        private T _Parameter;

        public T Parameter
        {
            get { return _Parameter; }
            set { _Parameter = value; }
        }

        private ProjectHistory _History;

        public ProjectHistory History
        {
            get { return _History; }
            set { _History = value; }
        }

        public DateTime RecentUsed
        {
            get { return History == null ? DateTime.MinValue : this.History.RecentUsed; }
        }

        public DateTime RecentUsedAction
        {
            get { return History == null ? DateTime.MinValue : this.History.RecentUsedAction; }
        }

        public Project()
        {

        }
    }
}
